// 复制到剪切板
export function XmCopy(str) {
  console.log('复制')

  var input = str + ''
  const el = document.createElement('textarea')
  el.value = input
  el.setAttribute('readonly', '')
  el.style.contain = 'strict'
  el.style.position = 'absolute'
  el.style.left = '-9999px'
  el.style.fontSize = '12pt' // Prevent zooming on iOS

  const selection = getSelection()
  var originalRange = false
  if (selection.rangeCount > 0) {
    originalRange = selection.getRangeAt(0)
  }
  document.body.appendChild(el)
  el.select()
  el.selectionStart = 0
  el.selectionEnd = input.length

  var success = false
  try {
    success = document.execCommand('copy')
  } catch (error) {
    console.log('error =' + JSON.stringify(error))
  }

  document.body.removeChild(el)

  if (originalRange) {
    selection.removeAllRanges()
    selection.addRange(originalRange)
  }

  return success
}

import { rejects } from 'assert'
// 弹窗
import { ElMessageBox, ElLoading, ElMessage } from 'element-plus'
import { resolve } from 'path'
function XmAlert(title, cb) {
  ElMessageBox.confirm(title, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(() => {
      if (cb) cb()
    })
    .catch((msg) => {
      console.log('msg =' + msg)
    })
}

function syncAlert(title, isHtml = false) {
  return new Promise((resolve, reject) => {
    if (!title) {
      resolve()
      return
    }
    ElMessageBox.confirm(title, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: isHtml,
      center: true,
    })
      .then(() => {
        resolve()
      })
      .catch((msg) => {
        reject()
      })
  })
}
function XmLoading(b) {
  const loading = ElLoading.service()
  if (!b) {
    loading.close()
  }
}

function XmMessage(index = 0, message) {
  const array = ['success', 'warning', 'info', 'error']
  ElMessage({ message, type: array[index] })
}

// 获取url中的参数
function getQueryString(path) {
  if (!path) return {}
  const arr = path.split('?')
  const keypath = {}
  if (arr.length >= 2) {
    const kvs = arr[1].split('&')
    kvs.map((kv) => {
      const tmps = kv.split('=')
      if (tmps.length >= 2) {
        keypath[tmps[0]] = tmps[1]
      }
    })
    return keypath
  }
  return {}
}

/**
 * 获取URL中的文件名
 * @param {*} url
 * @returns
 */
function getUrlName(url) {
  return url.split('/').pop()
}

/**
 * 去掉压缩后的json转译符 并转成对象
 * @param {*} str
 * @returns strObject
 */
function initJSONWithTranslator(str) {
  const tmp = str.replace(/\\"/g, '"')
  return JSON.parse(tmp)
}

/**
 * 简单加盐
 */
function addSalt(md5String = '') {
  const indexArray = []
  for (let index = 0; index < md5String.length; index++) {
    // 这里可以根据账号长度进行取余变换
    if (index % 3 === 0 && index !== 0) {
      indexArray.push(index + indexArray.length)
    }
  }

  let md5Array = md5String.split('')

  indexArray.forEach((item) => {
    // 后台要求加入的盐值
    md5Array.splice(item, 0, 'sb')
  })

  return md5Array.join('')
}

//截取视频第一帧作为播放前默认图片
function findvideocover(url, file, ref, isBackFile = false) {
  return new Promise((resolve, reject) => {
    // const  video = document.getElementById("myvideo"); // 获取视频对象
    const video = document.createElement('video') // 也可以自己创建video
    if (!video) return reject(new Error('video对象获取为空'))
    video.src = url // url地址 url跟 视频流是一样的

    // var canvas = document.getElementById('mycanvas') // 获取 canvas 对象
    var canvas = document.createElement('canvas') // 获取 canvas 对象
    const ctx = canvas.getContext('2d') // 绘制2d
    video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
    video.currentTime = 1 // 第一帧

    video.oncanplay = async () => {
      console.log(video.clientWidth, video.clientHeight)
      canvas.width = video.clientWidth ? video.clientWidth : 320 // 获取视频宽度
      canvas.height = video.clientHeight ? video.clientHeight : 320 //获取视频高度
      // 利用canvas对象方法绘图
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      // 转换成base64形式
      const videoFirstimgsrc = canvas.toDataURL('image/png') // 截取后的视频封面
      file.url = videoFirstimgsrc
      // base64转成bolb fileBolb文件 或者 base64
      let backFile = isBackFile
        ? base64toFile(videoFirstimgsrc, getFileName(file))
        : file.url
      // // 把首图上传生成云上地址
      // this.getFirstPngUrl(fileBolb)
      video.remove()
      canvas.remove()
      if (backFile) {
        return resolve(backFile)
      } else {
        return reject(new Error('转换成结果时出错'))
      }
    }
  })
}
function base64toFile(baseUrl, filename = 'file') {
  let arr = baseUrl.split(',')
  let type = arr[0].match(/:(.*?);/)[1] // 解锁图片类型
  let bytes = atob(arr[1]) // 解码base64
  let n = bytes.length
  let bufferArray = new Uint8Array(n)
  while (n--) {
    bufferArray[n] = bytes.charCodeAt(n)
  }
  return new File([bufferArray], filename, { type })
}
function getFileName(file) {
  const type = file.raw.type.split('/')[1]
  let name = ''
  if (type) {
    name = file.raw.name.substring(0, file.raw.name.indexOf(`.${type}`))
  }
  return `${name}.png`
}

function randomWord(range = 4) {
  var str = '',
    pos,
    arr = [
      '0',
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'i',
      'j',
      'k',
      'l',
      'm',
      'n',
      'o',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'I',
      'J',
      'K',
      'L',
      'M',
      'N',
      'O',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z',
    ]
  for (let i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

function checkPassword(test) {
  let strongRegex = new RegExp(
    '^(?=.{8,})(?=.*[A-Za-z_])(?=.*[0-9])(?=.*\\W).*$',
    'g'
  )
  return strongRegex.test(test)
}
function getExtByName(url) {
  if (!url) return ''
  const imgExt = {
    jpg: 'img',
    png: 'img',
    jpeg: 'img',
    gif: 'img',
    GIF: 'img',
    mp4: 'video',
    pdf: 'pdf',
  }

  // 预处理hash
  let index = url.lastIndexOf('?')
  if (index != -1) url = url.slice(0, index)

  // 获取index
  let startWith = url && url.lastIndexOf('.')
  if (!startWith || startWith == -1) return ''

  let ext = url.slice(startWith + 1)
  return imgExt[ext]
}

// function checkFile(file) {
//   if (file.response) {
//     return file.response.url
//   } else if () {
//
//   }
// }
export default {
  XmAlert,
  XmLoading,
  XmMessage,
  XmCopy,
  getQueryString,
  getUrlName,
  initJSONWithTranslator,
  syncAlert,
  addSalt,
  findvideocover,
  randomWord,
  checkPassword,
  getExtByName,
}
